package tongcheng.com.tongcheng.base.main.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.RequestMethod;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.adapter.SendOrderAdapter;
import tongcheng.com.tongcheng.base.BaseActivity;
import tongcheng.com.tongcheng.base.main.MainActivity;
import tongcheng.com.tongcheng.bean.MyCityBean;
import tongcheng.com.tongcheng.bean.StatusBean;
import tongcheng.com.tongcheng.bean.UpImageBean;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.utils.GetJsonDataUtil;
import tongcheng.com.tongcheng.utils.GsonUtil;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;

public class SendOrdersActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.title_bar)
    RelativeLayout mBg;
    @Bind(R.id.sendorders_rc)
    RecyclerView mSendordersRc;
    @Bind(R.id.sendorders_ok)
    Button mSendordersOk;
    @Bind(R.id.back_text)
    TextView mBackText;
    @Bind(R.id.sendorders_yusuan)
    EditText mSendordersYusuan;
    @Bind(R.id.sendorders_dianpuname)
    EditText mSendordersDianpuname;
    @Bind(R.id.sendorders_dianpuphone)
    EditText mSendordersDianpuphone;
    @Bind(R.id.sendorders_dianpuarea)
    EditText mSendordersDianpuarea;
    @Bind(R.id.sendorders_name)
    EditText mSendordersName;
    @Bind(R.id.sendorders_phone)
    EditText mSendordersPhone;
    @Bind(R.id.sendorders_starttime)
    TextView mSendordersStarttime;
    @Bind(R.id.sendorders_endtime)
    TextView mSendordersEndtime;
    @Bind(R.id.sendorders_shigong)
    EditText mSendordersShigong;
    @Bind(R.id.sendorders_info)
    EditText mSendordersInfo;
    @Bind(R.id.sendorders_gaishu)
    EditText mSendordersGaishu;
    @Bind(R.id.sendorders_dianpushengshiqu)
    TextView mSendordersDianPuShengshiqu;

    @Override
    public Integer initResid() {

        return R.layout.activity_send_orders;
    }

    int x = -1, y = -1, z = -1;
    String tx;

    private List<LocalMedia> selectList;
    public static List<String> filepath = new ArrayList<>();
    public static List<String> filename = new ArrayList<>();
    public static SendOrderAdapter mSendOrderAdapter;
    int temp = 0;
    public  void  showTimePicker(final int temps) {
        //时间选择器
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
             /*   tvTime.setText(getTime(date));*/
                if (temp == 1) {
                    //开始时间
                    mSendordersStarttime.setTextColor(Color.BLACK);
                    mSendordersStarttime.setText(getTimes(date));
                } else if (temp == 2) {
                    //结束时间
                    mSendordersEndtime.setTextColor(Color.BLACK);
                    mSendordersEndtime.setText(getTimes(date));
                }
            }
        })
                .setType(new boolean[]{true,true,true,false,false,false})
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }



    private String getTimes(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        filepath.clear();
        filename.clear();
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {

        if (thread == null) {//如果已创建就不再重新创建子线程了
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 写子线程中的操作,解析省市区数据
                    initJsonData();
                }
            });
            thread.start();
        }

        settitlebar(mBg);
        mTitle.setText("发布订单");
        mTitle.setTextColor(Color.BLACK);
        mBg.setBackgroundColor(0xffffea00);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        selectList = (List<LocalMedia>) getIntent().getSerializableExtra("zhaopian");
        if(selectList != null && selectList.size() > 0 ){
            UpImage(selectList);
        }

        mSendordersDianPuShengshiqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShowPickerView();
            }
        });

        mSendordersStarttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                temp = 1;
                showTimePicker(temp);
            }
        });

        mSendordersEndtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                temp = 2;
                showTimePicker(temp);
            }
        });

        mSendordersOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String gaishu = mSendordersGaishu.getText().toString().trim();
                String yusuan = mSendordersYusuan.getText().toString().trim();
                String dianpuname = mSendordersDianpuname.getText().toString().trim();
                String dianpuphone = mSendordersDianpuphone.getText().toString().trim();
                String dianpuarea = mSendordersDianpuarea.getText().toString().trim();
                String shengshiqu = mSendordersDianPuShengshiqu.getText().toString().trim();
                String name = mSendordersName.getText().toString().trim();
                String phone = mSendordersPhone.getText().toString().trim();
                String start = mSendordersStarttime.getText().toString().trim();
                String end = mSendordersEndtime.getText().toString().trim();
                String shigong = mSendordersShigong.getText().toString().trim();
                String info = mSendordersInfo.getText().toString().trim();

                if (TextUtils.isEmpty(gaishu)) {
                    ShowToast.showToast("请输入安装概述");
                }else if (TextUtils.isEmpty(yusuan)) {
                    ShowToast.showToast("请输入订单预算费用");
                } else if (TextUtils.isEmpty(dianpuname)) {
                    ShowToast.showToast("请输入您的店铺名称");
                }else if (TextUtils.isEmpty(dianpuphone)) {
                    ShowToast.showToast("请输入您的店铺联系方式");
                }else if(TextUtils.isEmpty(shengshiqu)){
                    ShowToast.showToast("请输入您的店铺地区");
                }
                else if (TextUtils.isEmpty(dianpuarea)) {
                    ShowToast.showToast("请输入您的店铺地址");
                }else if (TextUtils.isEmpty(name)) {
                    ShowToast.showToast("请输入负责人姓名");
                }else if (TextUtils.isEmpty(phone)) {
                    ShowToast.showToast("请输入负责人电话");
                }else if (TextUtils.isEmpty(start)) {
                    ShowToast.showToast("请输入预期开始施工时间");
                }else if (TextUtils.isEmpty(end)) {
                    ShowToast.showToast("请输入预期完工时间");
                }else if (TextUtils.isEmpty(shigong)) {
                    ShowToast.showToast("请输入施工所需人员");
                } else if (TextUtils.isEmpty(info)) {
                    ShowToast.showToast("请输入施工信息");
                } else {
                    UpInfo();
                }



            }
        });

        mSendOrderAdapter = new SendOrderAdapter(filepath, this, this, mBg);
        mSendordersRc.setAdapter(mSendOrderAdapter);

    }
    //上传信息
    private void UpInfo() {
        StringBuffer sb = new StringBuffer();
        MyRequest request = new MyRequest(ConStans.SendOrder_Url, RequestMethod.POST);
        request.add("account_id", Setting.getId());
        request.add("order_type", Setting.getShenfen());
        request.add("price", mSendordersYusuan.getText().toString().trim());
        request.add("shop_name", mSendordersDianpuname.getText().toString().trim());
        request.add("shop_phone", mSendordersDianpuphone.getText().toString().trim());
        request.add("shop_address", mSendordersDianpuarea.getText().toString().trim());
        request.add("principal", mSendordersName.getText().toString().trim());
        request.add("phone", mSendordersPhone.getText().toString().trim());
        if (filename.size() > 0) {
            for (int i = 0; i < filename.size(); i++) {
                sb.append(filename.get(i) + ",");
            }
        }
        request.add("scene_pic", sb.toString());
        request.add("scene_comment", mSendordersInfo.getText().toString().trim());
        request.add("order_title", mSendordersGaishu.getText().toString().trim());
        request.add("work_num", mSendordersShigong.getText().toString().trim());
        request.add("expect_start_time", mSendordersStarttime.getText().toString().trim());
        request.add("expect_end_time", mSendordersEndtime.getText().toString().trim());
        request.add("shop_province",shen);
        request.add("shop_city",shi);
        request.add("shop_area",qu);
        Log.e("省市区",shen + shi + qu);
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                StatusBean statusBean = GsonUtil.GsonToBean(json, StatusBean.class);
                if (statusBean != null) {
                    if (statusBean.msg != null) {
                        ShowToast.showToast(statusBean.msg);
                    }

                    if (statusBean.status == 1) {
                        startactivity(SendOrdersActivity.this, MainActivity.class);
                        finish();
                    }
                }
            }
        });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // ShowToast.showToast("我被回调了");
                  /*  for (LocalMedia localMedia : selectList) {
                        Log.e("tag", localMedia.getPath());
                        filepath.add(localMedia.getPath());
                        mSendOrderAdapter.notifyDataSetChanged();
                    }*/
                    UpImage(selectList);
                    break;
            }
        }
    }


    //上传图片
    private void UpImage(List<LocalMedia> selectList) {
        MyRequest request = new MyRequest(ConStans.UpImage_Url, RequestMethod.POST);
        request.add("code", "image");
        request.add("num", selectList.size());
        Log.e("size", selectList.size() + "");
        for (int i = 0; i < selectList.size(); i++) {
            boolean bb = selectList.get(i).isCompressed();
            if(bb){
                request.add("image" + (i + 1), new FileBinary(new File(selectList.get(i).getCompressPath())));
            }else {
                request.add("image" + (i + 1), new FileBinary(new File(selectList.get(i).getPath())));
            }

        }
        // request.add("picture", new FileBinary(new File(selectList.get(0).getPath())));
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                UpImageBean upImageBean = GsonUtil.GsonToBean(json, UpImageBean.class);
                if (upImageBean != null) {
                    for (int i = 0; i < upImageBean.data.size(); i++) {
                        filepath.add(ConStans.BaseUrl_Test_url + upImageBean.data.get(i).filename);
                        filename.add(upImageBean.data.get(i).filename);
                    }

                    mSendOrderAdapter.notifyDataSetChanged();
                }


            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    String shen = "";
    String shi = "";
    String qu = "";

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                x = options1;
                y = options2;
                z = options3;

                if (options1Items.get(options1).getV().equals(options2Items.get(options1).get(options2)

                )) {
                    tx =
                            options2Items.get(options1).get(options2) +
                                    options3Items.get(options1).get(options2).get(options3);

                    shen = options2Items.get(options1).get(options2);
                    shi = options2Items.get(options1).get(options2);
                    qu = options3Items.get(options1).get(options2).get(options3);
                } else {
                    tx = options1Items.get(options1).getV() +
                            options2Items.get(options1).get(options2) +
                            options3Items.get(options1).get(options2).get(options3);

                    shen = options1Items.get(options1).getV();
                    shi = options2Items.get(options1).get(options2);
                    qu = options3Items.get(options1).get(options2).get(options3);
                }

                //tv_address.setText("所在地址 :"+tx);
                mSendordersDianPuShengshiqu.setTextColor(ContextCompat.getColor(SendOrdersActivity.this,R.color.dan_bloack));
                mSendordersDianPuShengshiqu.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(datas, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private boolean isLoaded = false;

    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;


    private ArrayList<MyCityBean> options1Items = new ArrayList<>();
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:

                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(SendOrdersActivity.this, "省市区数据损坏，请重新下载应用", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };
    ArrayList<String> datas;
    String JsonData;
    ArrayList<MyCityBean> jsonBean;


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        JsonData = new GetJsonDataUtil().getJson(this, "city.json");//获取assets目录下的json文件数据
        Log.e("jsonsld", JsonData);
        jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        datas = new ArrayList<>();
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {
            datas.add(jsonBean.get(i).getV());

        }

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getN().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getN().get(c).getV().toString();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getN().get(c).getN() == null
                        || jsonBean.get(i).getN().get(c).getN().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getN().get(c).getN().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getN().get(c).getN().get(d).getV().toString();

                        City_AreaList.add(AreaName.toString());//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<MyCityBean> parseData(String result) {//Gson 解析
        ArrayList<MyCityBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                MyCityBean entity = gson.fromJson(data.optJSONObject(i).toString(), MyCityBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
